﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace AwesomeEnginePC.Networking.Sockets
{
    public class SocketServer<T> : BaseSocketConnection<T> where T : BaseBrodcastMessage, new()
    {
        List<Socket> clientSockets;
        Socket listenSocket;
        AsyncCallback workerWaitForData;

        public SocketServer(int port)
        {
            clientSockets = new List<Socket>();
            workerWaitForData = new AsyncCallback(OnDataReceived);

            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

            listenSocket.Bind(ipLocal);
            listenSocket.Listen(4);
            listenSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            AddToQueue(SocketMessage.MessageType.Init, null, true, null);
        }

        public void OnClientConnect(IAsyncResult asyn)
        {
            Socket newConnectionSocket = listenSocket.EndAccept(asyn);
            clientSockets.Add(newConnectionSocket);

            T message = new T();
            message.IsFromServer = false;

            AddToQueue(SocketMessage.MessageType.NewConnection, message, asyn.IsCompleted, GetClientSocketIndex(newConnectionSocket));

            listenSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            WaitForData(newConnectionSocket);
        }

        public void SendMessage(T message, int clientIndex)
        {
            Socket socketToUse = clientSockets[clientIndex];
            SendData(message, socketToUse);
        }

        protected override int? GetClientSocketIndex(Socket socket)
        {
            int index = clientSockets.IndexOf(socket);

            return index;
        }

    }
}
